package com.dameng.security;

import com.dameng.system.service.PermissionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

public class DMFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private PermissionService permissionService;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        Map<String, Collection<ConfigAttribute>> map = permissionService.getPermissionMap();
        FilterInvocation filterInvocation = (FilterInvocation) o;
        logger.debug(filterInvocation.getFullRequestUrl());  // 请求地址

        if (isMatcherAllowedRequest(filterInvocation)) {
            return null; //允许访问，不拦截
        }

        HttpServletRequest request = filterInvocation.getHttpRequest();
        //URL规则匹配.
        AntPathRequestMatcher matcher;
        for (Map.Entry<String, Collection<ConfigAttribute>> entry : map.entrySet()) {
            matcher = new AntPathRequestMatcher(entry.getKey());
            if (matcher.matches(request)) {
                return entry.getValue();
            }
        }
        //没有匹配到，设置默认角色
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    private boolean isMatcherAllowedRequest(FilterInvocation fi){
        return allowedRequest().stream().map(AntPathRequestMatcher::new)
                .filter(requestMatcher -> requestMatcher.matches(fi.getHttpRequest()))
                .toArray().length > 0;
    }

    private List<String> allowedRequest(){
        return Arrays.asList("/login");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
